package fr.gmdev.mail.fonction.ws;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;

public class ClientWSDepot {

	//	private String adsServer = "localhost" ;
	//	
	//	private int adsServerPort = 8080;

	private String adsUri = "/jdc/seam/resource/rest/mail";

	private HttpClient client = new HttpClient();
	private HostConfiguration config = new HostConfiguration();



	public ClientWSDepot(String adsServer, int adsServerPort, String adsUri) {
		super();
		//		this.adsServer = adsServer;
		//		this.adsServerPort = adsServerPort;
		this.adsUri = adsUri;
		config.setHost(adsServer, adsServerPort, "http");
	}



	public void postMessage(Mail mail) throws MessagingException, IOException{

		client.setHostConfiguration(config);

		Collection<MailAddress> destinataires = mail.getRecipients();
		MailAddress to = destinataires.iterator().next();
		MailAddress from = mail.getSender();
		String id = mail.getName();
		PostMethod post = new PostMethod(adsUri + "/" + to + "/" + from + "/" + id);

		post.addRequestHeader("Content-type", "application/octet-stream");


		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		mail.getMessage().writeTo(bos);
		ByteArrayRequestEntity re = new ByteArrayRequestEntity(bos.toByteArray());

		post.setRequestEntity(re);

		int status = client.executeMethod(post);
		System.out.println(status);
		System.out.println(post.getResponseBodyAsString());
		System.out.println(post.getStatusCode() + " - " + post.getStatusText());
		if (status != 200){
			// on rejette le mail
			throw new MessagingException("Le serveur a renvoye une erreur " + status);
		}

	}

	
	public void postMimeMessage(MimeMessage message) throws MessagingException, IOException{
		
		client.setHostConfiguration(config);
		
		InternetAddress to = (InternetAddress) message.getAllRecipients()[0];
		InternetAddress from = null ;
		try {
			from = (InternetAddress)message.getFrom()[0];
		} catch (Exception e) {
			//  cas des from tordus
			List<Address> addresses = new ArrayList<Address>();
			String[] rp = message.getHeader("Return-Path");
			if (rp != null && rp.length>0){
				for (String adrs : rp) {
					from = new InternetAddress(adrs);
					break;
				}
				
			}
		}
		
		System.out.println(adsUri + "/" + to.getAddress() + "/" + from.getAddress() + "/" + message.getContentID());
		PostMethod post = new PostMethod(adsUri + "/" + to.getAddress() + "/" + from.getAddress() + "/" + message.getContentID());
		
		post.addRequestHeader("Content-type", "application/octet-stream");


		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		message.writeTo(bos);
		ByteArrayRequestEntity re = new ByteArrayRequestEntity(bos.toByteArray());

		post.setRequestEntity(re);

		int status = client.executeMethod(post);
		System.out.println(status);
		System.out.println(post.getResponseBodyAsString());
		System.out.println(post.getStatusCode() + " - " + post.getStatusText());
		if (status != 200){
			// on rejette le mail
			throw new MessagingException("Le serveur a renvoye une erreur " + status);
		}
	}
	
	
	public static void main(String[] args) throws IOException {
		FileInputStream fis = null;
		
		File file = null ;
		
		try {
			file = new File("/home/gilbert/tmp/recup/recup");
			
			File[] files = file.listFiles();
			for (File fileatraiter : files) {
				fis = new FileInputStream(fileatraiter);
				System.out.println("traitement  de : " + fileatraiter.getName());
				MimeMessage message = new MimeMessage(null, fis);
//				ClientWSDepot client = new ClientWSDepot("gaston3.prod.extelia.fr", 8080, "/jdc/seam/resource/rest/mail");
				ClientWSDepot client = new ClientWSDepot("localhost", 8080, "/jdc/seam/resource/rest/mail");
				client.postMimeMessage(message);
				
			}
			
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			fis.close();
		}
		
	}
}
